import { baseUrl } from '../../../utils/config'
const { get } = require("../../../utils/request");
const EventBus = require('../../../utils/eventBus.js')
const { shared, timing, Easing, runOnJS } = wx.worklet;

wx.onBeforePageUnload(() => {
  EventBus.emit('setting.checkFamilyInfo')
  EventBus.emit('home.freshAllData')
})

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showPageContainer: true,
    showParentPop: false,
    targetDeleteChildId: '',
    showErrorPwdTip: false,
    showErrorPwdTipChild: false,
    showDeleteChild: false,
    unbindParent: {},
    focusInputPwd: false,
    focusInputPwdChild: false,
    passwordInputValue: '',
    passwordInputValueChild: '',
    pwdValue: ['', '', '', ''],
    pwdValueChild: ['', '', '', ''],
    show: false,
    duration: 300,
    round: true,
    position: 'bottom',
    overlay: true,
    w_owner: {},
    w_father: {},
    w_mother: {},
    w_children: {},
    showAddChildBtn: false,
    baseUrl: baseUrl,
    father: {
      id: -1,
      memberName: '--',
      headPicPath: "user.png"
    },
    mother: {
      id: -1,
      memberName: '--',
      headPicPath: "user.png"
    },
    showAddChildren: false,
    directionFlag: {},
    fatherCardOpen: false,
    motherCardOpen: false,
    childrenAnimal: [],
    childrens: [],
    motherAnimal: {
      cardX: {},
      bindX: {},
      modifyX: {}
    },
    fatherAnimal: {
      cardX: {},
      bindX: {},
      modifyX: {}
    },


  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.freshChild();
  },


  addAnimalCode() {
    this.data.directionFlag.value = 0;
    this.data.motherAnimal.cardX.value = 0;
    this.data.motherAnimal.bindX.value = 0;
    this.data.motherAnimal.modifyX.value = 0;
    this.data.fatherAnimal.cardX.value = 0;
    this.data.fatherAnimal.bindX.value = 0;
    this.data.fatherAnimal.modifyX.value = 0;

    this.data.childrenAnimal.forEach((item, index) => {
      item.cardX = shared(0)
      item.modifyX = shared(0)
      item.deleteX = shared(0)
      item.cardX.value = 0;
      item.modifyX.value = 0;
      item.deleteX.value = 0;

      this.applyAnimatedStyle(`.card-index-${index}`, () => {
        'worklet';
        return {
          transform: `translateX(${item.cardX.value}px)`,
        };
      });

      this.applyAnimatedStyle(`.modify-index-${index}`, () => {
        'worklet';
        return {
          transform: `translateX(${item.modifyX.value}px)`,
        };
      });

      this.applyAnimatedStyle(`.delete-index-${index}`, () => {
        'worklet';
        return {
          transform: `translateX(${item.deleteX.value}px)`,
        };
      });
    })

    this.applyAnimatedStyle(`.mother-card-infor`, () => {
      'worklet';
      const vx = this.data.motherAnimal.cardX.value;
      return {
        transform: `translateX(${vx}px)`,
      };
    });

    this.applyAnimatedStyle(`.mother-cancel-bind`, () => {
      'worklet';
      const vx = this.data.motherAnimal.bindX.value;
      return {
        transform: `translateX(${vx}px)`,
      };
    });

    this.applyAnimatedStyle(`.mother-modify-info`, () => {
      'worklet';
      const vx = this.data.motherAnimal.modifyX.value;
      return {
        transform: `translateX(${vx}px)`,
      };
    });

    this.applyAnimatedStyle(`.father-card-infor`, () => {
      'worklet';
      const vx = this.data.fatherAnimal.cardX.value;
      return {
        transform: `translateX(${vx}px)`,
      };
    });

    this.applyAnimatedStyle(`.father-cancel-bind`, () => {
      'worklet';
      const vx = this.data.fatherAnimal.bindX.value;
      return {
        transform: `translateX(${vx}px)`,
      };
    });

    this.applyAnimatedStyle(`.father-modify-info`, () => {
      'worklet';
      const vx = this.data.fatherAnimal.modifyX.value;
      return {
        transform: `translateX(${vx}px)`,
      };
    });
  },

  addChildren() {
    if (this.data.father.id == -1 && this.data.mother.id == -1) {
      wx.showToast({
        title: '请先填写父母信息',
        icon: 'error',
        duration: 2000
      })
      return;
    }
    wx.navigateTo({
      url: '/pages/me/family/children/children',
    })
  },

  onTouchChildEnd({ currentTarget: { id } }) {
    const child = this.data.childrens[id];
    if (!child.opened) {
      wx.navigateTo({
        url: `/pages/me/family/childrenDetail/childrenDetail?id=${child.id}`,
      })
    } else {
      this.closeChildrenCard(id);
    }

  },
  updateChildren(index, openedFlag) {
    this.data.childrens[index].opened = openedFlag
  },

  fobiddenOpen(type, openedFlag) {
    if (type == "F") {
      this.data.fatherCardOpen = openedFlag;
    } else {
      this.data.motherCardOpen = openedFlag;
    }
  },

  onGestureEvent(e) {
    'worklet'
    const { deltaX, state, currentTarget: { dataset: { index } } } = e;
    const child = this.data.childrenAnimal[index];
    const tempX = child.cardX.value + deltaX;
    const cardOpenX = -130;
    const modifyOpenX = -72;
    const deleteOpenX = -26;
    const durationTime = 600;
    const animalBezier = Easing.bezier(.16, .53, .18, .82);

    if (deltaX > 0) {
      this.data.directionFlag.value = 1;
    } else if (deltaX < 0) {
      this.data.directionFlag.value = -1;
    }

    if (state == 2) {
      if (tempX > 0) {
        child.cardX.value = 0;
        child.deleteX.value = 0;
        child.modifyX.value = 0;
      } else {
        let calculateX = deltaX;
        if (child.cardX.value < cardOpenX) {
          const n1 = Math.abs(child.cardX.value + deltaX) + cardOpenX;
          calculateX = deltaX * (1 - n1 * 1.0 / 50)
        }

        child.cardX.value += calculateX;
        child.deleteX.value += calculateX * 0.2;
        child.modifyX.value += calculateX * 0.55;

      }
    } else if (state == 3) {
      if (this.data.directionFlag.value > 0 || child.cardX.value > -30) {
        runOnJS(this.updateChildren)(index, false)

        child.cardX.value = timing(0, {
          duration: durationTime,
          easing: animalBezier,
        });
        child.deleteX.value = timing(0, {
          duration: durationTime,
          easing: animalBezier,
        });
        child.modifyX.value = timing(0, {
          duration: durationTime,
          easing: animalBezier,
        });
      } else {
        runOnJS(this.updateChildren)(index, true);

        child.cardX.value = timing(cardOpenX, {
          duration: durationTime,
          easing: animalBezier,
        });
        child.deleteX.value = timing(deleteOpenX, {
          duration: durationTime,
          easing: animalBezier,
        });
        child.modifyX.value = timing(modifyOpenX, {
          duration: durationTime,
          easing: animalBezier,
        });
      }
    }
  },
  closeParentsCard(index) {
    let cardX, modifyX, bindX;
    const durationTime = 600;
    const animalBezier = Easing.bezier(.16, .53, .18, .82);

    if (index == 'M') {
      cardX = this.data.motherAnimal.cardX;
      bindX = this.data.motherAnimal.bindX;
      modifyX = this.data.motherAnimal.modifyX;
    } else {
      cardX = this.data.fatherAnimal.cardX;
      bindX = this.data.fatherAnimal.bindX;
      modifyX = this.data.fatherAnimal.modifyX;
    }

    this.fobiddenOpen(index, false)
    cardX.value = timing(0, {
      duration: durationTime,
      easing: animalBezier,
    });
    bindX.value = timing(0, {
      duration: durationTime,
      easing: animalBezier,
    });
    modifyX.value = timing(0, {
      duration: durationTime,
      easing: animalBezier,
    });

  },
  closeChildrenCard(index) {
    const durationTime = 600;
    const animalBezier = Easing.bezier(.16, .53, .18, .82);
    const child = this.data.childrenAnimal[index];
    this.updateChildren(index, false)

    child.cardX.value = timing(0, {
      duration: durationTime,
      easing: animalBezier,
    });
    child.deleteX.value = timing(0, {
      duration: durationTime,
      easing: animalBezier,
    });
    child.modifyX.value = timing(0, {
      duration: durationTime,
      easing: animalBezier,
    });
  },
  onMotherGestureEvent(e) {
    'worklet'
    const { deltaX, state, currentTarget: { dataset: { index } } } = e;

    let cardX, modifyX, bindX;
    if (index == 'M') {
      cardX = this.data.motherAnimal.cardX;
      bindX = this.data.motherAnimal.bindX;
      modifyX = this.data.motherAnimal.modifyX;
    } else {
      cardX = this.data.fatherAnimal.cardX;
      bindX = this.data.fatherAnimal.bindX;
      modifyX = this.data.fatherAnimal.modifyX;
    }

    const tempX = cardX.value + deltaX;
    const cardOpenX = -130;
    const modifyOpenX = -72;
    const bindOpenX = -26;
    const durationTime = 600;
    const animalBezier = Easing.bezier(.16, .53, .18, .82);

    if (deltaX > 0) {
      this.data.directionFlag.value = 1;
    } else if (deltaX < 0) {
      this.data.directionFlag.value = -1;
    }

    if (state == 2) {
      if (tempX > 0) {
        cardX.value = 0;
        bindX.value = 0;
        modifyX.value = 0;
      } else {
        let calculateX = deltaX;
        if (cardX.value < cardOpenX) {
          const n1 = Math.abs(cardX.value + deltaX) + cardOpenX;
          calculateX = deltaX * (1 - n1 * 1.0 / 50)
        }

        cardX.value += calculateX;
        bindX.value += calculateX * 0.2;
        modifyX.value += calculateX * 0.55;
      }
    } else if (state == 3) {
      if (this.data.directionFlag.value > 0 || cardX.value > -30) {
        runOnJS(this.fobiddenOpen)(index, false)
        cardX.value = timing(0, {
          duration: durationTime,
          easing: animalBezier,
        });
        bindX.value = timing(0, {
          duration: durationTime,
          easing: animalBezier,
        });
        modifyX.value = timing(0, {
          duration: durationTime,
          easing: animalBezier,
        });
      } else {
        runOnJS(this.fobiddenOpen)(index, true);

        cardX.value = timing(cardOpenX, {
          duration: durationTime,
          easing: animalBezier,
        });
        bindX.value = timing(bindOpenX, {
          duration: durationTime,
          easing: animalBezier,
        });
        modifyX.value = timing(modifyOpenX, {
          duration: durationTime,
          easing: animalBezier,
        });

      }
    }

  },

  modifyChildInfo({ currentTarget: { id } }) {
    const child = this.data.childrens[id];
    wx.navigateTo({
      url: `/pages/me/family/children/children?id=${child.id}`,
    })
  },
  deleteChildInfo({ currentTarget: { id } }) {
    this.setData({
      targetDeleteChildId: id,
      show: true,
      showParentPop: false
    })
  },
  modifyParentsInfo({ currentTarget: { dataset: { type } } }) {
    const parentsName = type == "F" ? "爸爸" : "妈妈";
    const id = type == "M" ? this.data.mother.id : this.data.father.id;

    this.setData({
      showPageContainer: false
    })

    wx.navigateTo({
      url: `/pages/me/family/parents/parents?parentsName=${parentsName}&id=${id}`,
    })
  },
  showPageContainer() {
    this.setData({
      showPageContainer: true
    })
  },
  openParentsDetail({ currentTarget: { dataset: { type, id, index } } }) {
    const flag = type == "F" ? this.data.fatherCardOpen : this.data.motherCardOpen;
    const parentsName = type == "F" ? "爸爸" : "妈妈";

    if (!flag && id < 0) {
      wx.showToast({
        title: `请向左滑动填写`,
        icon: 'error',
        duration: 2000
      })
      return;
    }

    if (!flag) {
      wx.navigateTo({
        url: `/pages/me/family/parentsDetail/parentsDetail?parentsName=${parentsName}&id=${id}`,
      })
    } else {
      this.closeParentsCard(index)
    }
  },
  readyCancelBind({ currentTarget: { dataset: { type } } }) {
    const owner = wx.getStorageSync('owner')
    const unbindParent = type == "M" ? this.data.mother : this.data.father;
    const parentOwner = unbindParent.owner;
    this.setData({
      unbindParent: unbindParent
    })
    if (owner == parentOwner && parentOwner == 1) {
      this.setData({
        show: true,
        showParentPop: true
      })
    } else {
      this.cancelBindWx();
    }
  },
  cancelBindWx() {
    const id = this.data.unbindParent.id;
    const isBindWx = this.data.unbindParent.bindWx;
    if (!isBindWx) {
      return;
    }

    wx.showModal({
      title: '提示',
      content: '确定要解绑微信吗？',
      success(res) {
        if (res.confirm) {
          get('family/unbindWx', { id: id }, (unicode) => {
            wx.setStorageSync('unicode', unicode)
            wx.setStorageSync('owner', 1)
            EventBus.emit('home.freshAllData')
            wx.switchTab({
              url: '/pages/tabBar/summary/home',
            })
          })
        }
      }
    })
  },
  freshChild() {

    this.data.w_owner = shared(0);
    this.data.w_mother = shared(0);
    this.data.w_father = shared(0);
    this.data.w_children = shared(0);

    this.data.directionFlag = shared(0);
    this.data.motherAnimal.cardX = shared(0);
    this.data.motherAnimal.bindX = shared(0);
    this.data.motherAnimal.modifyX = shared(0);
    this.data.fatherAnimal.cardX = shared(0);
    this.data.fatherAnimal.bindX = shared(0);
    this.data.fatherAnimal.modifyX = shared(0);
    this.setData({
      motherCardOpen: false,
      fatherCardOpen: false
    })

    const unicode = wx.getStorageSync('unicode');
    const owner = wx.getStorageSync('owner');

    this.data.w_owner.value = owner;

    get('family/members', {
      "filter_unicode_eq_s": unicode,
      "orderBy": "birthday",
    }, ({ families, loginUser }) => {
      const children = [];
      const params = {
        father: {
          id: -1,
          memberName: '--',
          headPicPath: "user.png"
        },
        mother: {
          id: -1,
          memberName: '--',
          headPicPath: "user.png"
        },
      };
      this.data.childrenAnimal = [];

      families.forEach((item) => {
        if (item.memberAlias == '爸爸') {
          params.father = item;
          this.data.w_father.value = item;
        } else if (item.memberAlias == '妈妈') {
          params.mother = item;
          this.data.w_mother.value = item;
        } else {
          children.push(item);
          this.data.childrenAnimal.push({
            cardX: {},
            bindX: {},
            modifyX: {}
          })
        }
      })
      params.childrens = children;

      if (loginUser) {
        this.data.w_children.value = true
        if (children.length >= 3) {
          params.showAddChildren = false;
        } else {
          params.showAddChildren = true;
        }
      } else {
        this.data.w_children.value = false
        params.showAddChildren = false;
      }

      this.setData(params);
      this.addAnimalCode();
    })
  },

  checkFatherPermission() {
    'worklet'
    const father = this.data.w_father.value;
    if (father) {
      return father.canAction;
    } else {
      return true;
    }
  },
  checkMotherPermission() {
    'worklet'
    const mother = this.data.w_mother.value;
    if (mother) {
      return mother.canAction;
    } else {
      return true;
    }
  },
  checkChildPermission() {
    'worklet'
    return this.data.w_children.value;
  },

  clickPrivacy() {
    wx.navigateTo({
      url: '/pages/me/privacy/privacy',
    })
  },

  activeInputPassword() {
    this.setData({
      focusInputPwd: true
    })
  },

  activeInputPasswordChild() {
    this.setData({
      focusInputPwdChild: true
    })
  },

  inputPassword({ detail: { value } }) {
    const defaultValue = ['', '', '', '']
    value.split('').forEach((item, i) => {
      defaultValue[i] = item
    })
    this.setData({
      pwdValue: defaultValue
    })
    if (value.length == 4) {
      this.confirmUnbindWx();
    } else {
      this.setData({
        showErrorPwdTip: false
      })
    }
  },
  inputPasswordChild({ detail: { value } }) {
    const defaultValue = ['', '', '', '']
    const freshChild = this.freshChild.bind(this);
    const cancelBind = this.cancelBindChild.bind(this);
    value.split('').forEach((item, i) => {
      defaultValue[i] = item
    })
    this.setData({
      pwdValueChild: defaultValue
    })
    if (value.length == 4) {
      get(`family/deleteChild/${this.data.targetDeleteChildId}`, { password: this.data.passwordInputValueChild }, (data) => {
        if (data == '密码错误') {
          this.setData({
            showErrorPwdTipChild: true
          })
        } else {
          wx.showToast({
            title: '成功',
            icon: 'success',
            duration: 2000
          })
          setTimeout(() => {
            cancelBind();
            freshChild();
            wx.hideKeyboard()
          }, 2000);
        }
      })
    } else {
      this.setData({
        showErrorPwdTipChild: false
      })
    }
  },
  cancelBind() {
    this.setData({
      pwdValue: ['', '', '', ''],
      passwordInputValue: '',
      showErrorPwdTip: false,
      show: false
    })
  },
  cancelBindChild() {
    this.setData({
      pwdValueChild: ['', '', '', ''],
      passwordInputValueChild: '',
      showErrorPwdTipChild: false,
      show: false
    })
  },
  confirmUnbindWx() {
    get('family/unbindOwnerWx', {
      id: this.data.unbindParent.id,
      password: this.data.pwdValue.join('')
    }, (data) => {
      if (data == '密码错误') {
        this.setData({
          showErrorPwdTip: true
        })
        return;
      }

      wx.setStorageSync('unicode', data)
      wx.setStorageSync('owner', 1)

      wx.showToast({
        title: '成功',
        icon: 'success',
        duration: 2000,
        success: function () {
          EventBus.emit('home.freshAllData')
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/tabBar/summary/home',
            })
          }, 2000);
        }
      })
    })
  }
})

